<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      class PubSub {
        constructor() {
          this.subs = {};
        }

        // 订阅
        on(type, fn) {
          if (!this.subs[type]) {
            this.subs[type] = [];
          }
          this.subs[type].push(fn);
        }

        // 发布
        emit(type) {
          if (!this.subs[type]) {
            return;
          }
          for (const fn of this.subs[type]) {
            fn();
          }
        }
      }

      const sub = new PubSub();

      sub.on('click', function () {
        console.log('click1');
      });
      sub.on('click', function () {
        console.log('click2');
      });
      sub.on('hello', function () {
        console.log('hello1');
      });

      sub.emit('hello');
    </script>
  </body>
</html>
